my $file = $ARGV[0];

@rssi[300000];

open Input, "<$file" or die"cannot open $file\n";
$number = 0;
$firstline = 1;
$start = -1;
$end = -1;
while(<Input>){
	chomp;
	@rs = split;

	if($firstline==1) {$firstline=0; next;}
	$rssi[$number] = $rs[1];
	$number++;
	
}
close Input;
print ("number: $number\n");
	#get noise floor
	$i=0;
	$noise = 0;
	$sucNum = 0;
	for($i=1;$i<$number;$i++){
		if($rssi[$i]< -90 && $rssi[$i] >-100){
			if( abs($rssi[$i] - $rssi[$i-1]) <  3) {
				$sucNum++;
			}
			else {
				$sucNum = 0;
			}
		}
		#print ("$sucNum $rssi[$i]\n");
		if($sucNum>=100) {
			$noise = $rssi[$i-10];
			$sucNum = 0;				#set 0 after using.
			last;
		}
	}
print ("noise floor:$noise\n");

$i = 0;
$j = 0;
for($i=0;$i<$number;$i++) {
	if($rssi[$i]==$rssi[$i+1] && $rssi[$i+2]==$rssi[$i+1] && $rssi[$i] > -70 && $start == -1){
		$start = $i;
	}
	if($rssi[$i]==$rssi[$i+1] && $rssi[$i] < -90 && $start!=-1){
		$end = $i;
	}
	if($end!=-1){
		if(($end -$start)> 200){
			print ("$start\t $end\n");
			for($j=$start;$j<$end;$j++) {
				$rssi[$j] = $noise;
				print ("$j $rssi[$j]\n");
			}
			$start = -1;
			$end = -1;
		}
		else {
			$start  = -1;
			$end = -1;
		}
	}


}

$i=0;
open Output, ">$file" or die "cannot open $file\n";
for($i=0; $i < $number; $i++) {
	#print "$i $rssi[$i]\n";
	print Output "$i $rssi[$i]\n";
}
close Output;
